package com.szxydb.dmp.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.szxydb.dmp.common.CheckAdminToken;
import com.szxydb.dmp.common.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminTokenInterceptor implements HandlerInterceptor {

    @Autowired
    CheckAdminToken checkAdminToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String token = checkAdminToken.getTokenFormRequest(request);

        if (token == null || token.isEmpty()){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }

        Boolean result = checkAdminToken.check(token);
        if (!result){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        return true;
    }
}
